package com.dog.auth.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import com.dog.auth.config.captcha.CaptchaProperties;
import com.dog.auth.service.ImageCodeService;
import com.dog.framework.core.constant.CacheConstants;
import com.dog.framework.core.constant.Constants;
import com.dog.framework.core.enums.CaptchaEnum;
import com.dog.framework.redis.service.RedisService;
import com.dog.framework.core.exception.CaptchaException;
import com.dog.framework.core.exception.CaptchaExpireException;
import com.google.code.kaptcha.Producer;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.FastByteArrayOutputStream;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author liuxk
 * @date 2023/12/19 17:11
 *
 */
@Service
public class ImageCodeServiceImpl implements ImageCodeService {

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private CaptchaProperties captchaProperties;

    @Autowired
    private RedisService redisService;


    @Override
    public Map<String, Object> createCaptcha() throws IOException, CaptchaException {
        Map<String, Object> resutMap = new HashMap<>();
        boolean captchaOnOff = captchaProperties.getEnabled();
        resutMap.put("captchaOnOff", captchaOnOff);
        if (!captchaOnOff) {
            return resutMap;
        }

        // 保存验证码信息
        String uuid = IdUtil.simpleUUID();
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;

        String capStr = null;
        String code = null;
        BufferedImage image = null;

        String captchaType = captchaProperties.getType();
        // 生成验证码
        if (CaptchaEnum.MATH.getCode().equals(captchaType)) {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        } else if (CaptchaEnum.CHAR.getCode().equals(captchaType)) {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        redisService.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            throw new CaptchaException();
        }
        resutMap.put("uuid", uuid);
        resutMap.put("img", Base64.encode(os.toByteArray()));
        return resutMap;
    }

    @Override
    public void checkCaptcha(String code, String uuid) throws CaptchaException {
        if (StringUtils.isEmpty(code)) {
            throw new CaptchaException("user.jcaptcha.not.blank");
        }
        if (StringUtils.isEmpty(uuid)) {
            throw new CaptchaExpireException();
        }
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisService.get(verifyKey);
        if (StringUtils.isEmpty(captcha)) {
            throw new CaptchaException();
        }
        redisService.delete(verifyKey);
        if (!code.equalsIgnoreCase(captcha)) {
            throw new CaptchaException();
        }

    }
}
